# -*- coding: utf-8 -*-
"""
主窗口界面
"""
import sys
import os
from PyQt5.QtWidgets import (QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, 
                            QTabWidget, QLabel, QPushButton, QMessageBox, 
                            QStatusBar, QProgressBar, QSplitter)
from PyQt5.QtCore import Qt, QThread, pyqtSignal, QTimer
from PyQt5.QtGui import QIcon, QFont

from .connection_widget import ConnectionWidget
from .table_selection_widget import TableSelectionWidget
from .export_widget import ExportWidget
from .log_widget import LogWidget
from database.mysql_connector import MySQLConnector
from core.dict_extractor import DictExtractor
from core.export_manager import ExportManager

class ExportThread(QThread):
    """导出线程"""
    progress_updated = pyqtSignal(int, str)
    export_finished = pyqtSignal(bool, str)
    
    def __init__(self, dict_data, export_format, file_path, file_name, export_manager, overwrite=False):
        super().__init__()
        self.dict_data = dict_data
        self.export_format = export_format
        self.file_path = file_path
        self.file_name = file_name
        self.export_manager = export_manager
        self.overwrite = overwrite
    
    def run(self):
        """执行导出"""
        try:
            # 设置进度回调
            self.export_manager.set_progress_callback(self.progress_updated.emit)
            
            # 执行导出
            success, result = self.export_manager.export_database_dict(
                self.dict_data, self.export_format, self.file_path, self.file_name, self.overwrite
            )
            
            self.export_finished.emit(success, result)
            
        except Exception as e:
            self.export_finished.emit(False, f"导出异常: {str(e)}")
    
    def cancel(self):
        """取消导出"""
        self.export_manager.cancel_export()

class MainWindow(QMainWindow):
    """主窗口"""
    
    def __init__(self):
        super().__init__()
        self.mysql_connector = MySQLConnector()
        self.dict_extractor = DictExtractor(self.mysql_connector)
        self.export_manager = ExportManager()
        self.export_thread = None
        self.current_dict_data = {}
        
        self.init_ui()
        self.setup_connections()
        self.update_connection_status()
    
    def init_ui(self):
        """初始化界面"""
        self.setWindowTitle("MySQL数据库字典导出工具 v1.0.0")
        self.setGeometry(100, 100, 1200, 800)
        
        # 设置窗口图标
        self.setWindowIcon(QIcon())
        
        # 创建中央部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 创建主布局
        main_layout = QVBoxLayout(central_widget)
        
        # 创建状态栏
        self.setup_status_bar()
        
        # 创建标签页
        self.tab_widget = QTabWidget()
        main_layout.addWidget(self.tab_widget)
        
        # 创建各个标签页
        self.create_connection_tab()
        self.create_table_selection_tab()
        self.create_export_tab()
        self.create_log_tab()
        
        # 设置初始状态
        self.tab_widget.setCurrentIndex(0)
        self.update_tab_states()
    
    def setup_status_bar(self):
        """设置状态栏"""
        self.status_bar = QStatusBar()
        self.setStatusBar(self.status_bar)
        
        # 连接状态标签
        self.connection_status_label = QLabel("未连接")
        self.connection_status_label.setStyleSheet("color: red; font-weight: bold;")
        self.status_bar.addWidget(self.connection_status_label)
        
        # 进度条
        self.progress_bar = QProgressBar()
        self.progress_bar.setVisible(False)
        self.status_bar.addPermanentWidget(self.progress_bar)
        
        # 状态信息标签
        self.status_label = QLabel("就绪")
        self.status_bar.addPermanentWidget(self.status_label)
        
        # 帮助文档链接
        self.help_label = QLabel('<a href="https://mp.weixin.qq.com/s/Sfv7esEtsrLjdB0pnxdyOg" style="color: #28a745; text-decoration: none;">打  开  帮  助  文  档 &nbsp;&nbsp;&nbsp; </a>')
        self.help_label.setOpenExternalLinks(True)
        self.help_label.setStyleSheet("""
            QLabel {
                color: #28a745;
                font-size: 12px;
                text-decoration: none;
            }
            QLabel:hover {
                color: #1e7e34;
                text-decoration: underline;
            }
        """)
        # 添加到状态栏中间位置
        self.status_bar.insertPermanentWidget(1, self.help_label)
    
    def create_connection_tab(self):
        """创建连接标签页"""
        self.connection_widget = ConnectionWidget(self.mysql_connector)
        self.tab_widget.addTab(self.connection_widget, "数据库连接")
    
    def create_table_selection_tab(self):
        """创建表选择标签页"""
        self.table_selection_widget = TableSelectionWidget(self.dict_extractor)
        self.tab_widget.addTab(self.table_selection_widget, "表选择")
    
    def create_export_tab(self):
        """创建导出标签页"""
        self.export_widget = ExportWidget(self.export_manager)
        self.tab_widget.addTab(self.export_widget, "导出设置")
    
    def create_log_tab(self):
        """创建日志标签页"""
        self.log_widget = LogWidget(self.export_manager)
        self.tab_widget.addTab(self.log_widget, "导出日志")
    
    def setup_connections(self):
        """设置信号连接"""
        # 连接状态变化
        self.connection_widget.connection_changed.connect(self.on_connection_changed)
        
        # 表选择变化
        self.table_selection_widget.tables_selected.connect(self.on_tables_selected)
        
        # 导出相关信号
        self.export_widget.export_started.connect(self.on_export_started)
        self.export_widget.export_cancelled.connect(self.on_export_cancelled)
    
    def on_connection_changed(self, connected: bool):
        """连接状态变化处理"""
        self.update_connection_status()
        self.update_tab_states()
        
        if connected:
            # 连接成功，刷新表列表
            self.table_selection_widget.refresh_tables()
        else:
            # 连接断开，清空数据
            self.current_dict_data = {}
            self.table_selection_widget.clear_tables()
    
    def on_tables_selected(self, selected_tables: list):
        """表选择变化处理"""
        if selected_tables and self.mysql_connector.is_connected():
            # 提取字典数据
            self.current_dict_data = self.dict_extractor.extract_database_dict(selected_tables)
            self.export_widget.set_dict_data(self.current_dict_data)
        else:
            self.current_dict_data = {}
            self.export_widget.set_dict_data({})
        
        # 更新标签页状态
        self.update_tab_states()
    
    def on_export_started(self, export_format: str, file_path: str, file_name: str, overwrite: bool = False):
        """开始导出"""
        if not self.current_dict_data:
            QMessageBox.warning(self, "警告", "请先选择要导出的表")
            return
        
        # 创建导出线程
        self.export_thread = ExportThread(
            self.current_dict_data, export_format, file_path, file_name, self.export_manager, overwrite
        )
        
        # 连接信号
        self.export_thread.progress_updated.connect(self.on_export_progress)
        self.export_thread.export_finished.connect(self.on_export_finished)
        
        # 显示进度条
        self.progress_bar.setVisible(True)
        self.progress_bar.setValue(0)
        self.status_label.setText("正在导出...")
        
        # 禁用导出按钮
        self.export_widget.set_export_enabled(False)
        
        # 开始导出
        self.export_thread.start()
    
    def on_export_cancelled(self):
        """取消导出"""
        if self.export_thread and self.export_thread.isRunning():
            self.export_thread.cancel()
            self.export_thread.wait()
        
        self.progress_bar.setVisible(False)
        self.status_label.setText("导出已取消")
        self.export_widget.set_export_enabled(True)
    
    def on_export_progress(self, progress: int, message: str):
        """导出进度更新"""
        self.progress_bar.setValue(progress)
        self.status_label.setText(message)
    
    def on_export_finished(self, success: bool, result: str):
        """导出完成"""
        self.progress_bar.setVisible(False)
        self.export_widget.set_export_enabled(True)
        
        if success:
            self.status_label.setText("导出成功")
            QMessageBox.information(self, "导出成功", f"数据库字典已成功导出到:\n{result}")
            
            # 刷新日志
            self.log_widget.refresh_logs()
        else:
            self.status_label.setText("导出失败")
            QMessageBox.critical(self, "导出失败", f"导出失败:\n{result}")
    
    def update_connection_status(self):
        """更新连接状态"""
        if self.mysql_connector.is_connected():
            db_info = self.mysql_connector.get_database_info()
            db_name = db_info.get('database_name', '')
            self.connection_status_label.setText(f"已连接: {db_name}")
            self.connection_status_label.setStyleSheet("color: green; font-weight: bold;")
        else:
            self.connection_status_label.setText("未连接")
            self.connection_status_label.setStyleSheet("color: red; font-weight: bold;")
    
    def update_tab_states(self):
        """更新标签页状态"""
        connected = self.mysql_connector.is_connected()
        has_selected_tables = bool(self.current_dict_data)
        
        # 表选择标签页
        self.tab_widget.setTabEnabled(1, connected)
        
        # 导出标签页
        self.tab_widget.setTabEnabled(2, connected and has_selected_tables)
        
        # 调试信息（生产环境可注释掉）
        # print(f"标签页状态更新: 连接={connected}, 已选表={has_selected_tables}, 导出页启用={connected and has_selected_tables}")
    
    def closeEvent(self, event):
        """窗口关闭事件"""
        # 取消正在进行的导出
        if self.export_thread and self.export_thread.isRunning():
            self.export_thread.cancel()
            self.export_thread.wait()
        
        # 断开数据库连接
        self.mysql_connector.disconnect()
        
        event.accept()
